<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="valueHtml"
      style="height: 500px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
    <!-- @onInsertedImage="handleInsertedImage" -->
  </div>
</template>

<script setup>
import { uploadFile } from "@/api/common";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const mode = ref("default"); // default 或 'simple'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = defineModel();

const toolbarConfig = { excludeKeys: "" };
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: [] };
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义上传
  async customUpload(file, insertFn) {
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
    const params = new FormData();
    params.append("file", file);
    const res = await uploadFile(params);
    const { fullPath } = res.data;
    insertFn(fullPath, "", fullPath);
  }
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = editor => {
  // console.log(editor.getHtml());
};
</script>
<style scoped lang="scss"></style>
